$(function(){
	/* 查询所有零食类型 */
	queryType();
	/* ----------条件查询键盘按下事件末值判断---------- */ 
	$("#snacksNum2").keyup(function(){
		if($("#snacksNum2").val()<=$("#snacksNum").val()){
			layer.msg("必须大于起始价!");
			$("#snacksNum2").val(parseInt($("#snacksNum").val())+parseInt(1));
		}
	})
})
/**
 * 退货数量
 * @param obj
 * @returns
 */
function number(obj){
	var numbers = $(obj).val();
	var reg=/^[1-9]\d*$/;
	if(!reg.test(numbers)){
		layer.msg("只能输入正整数!");
		obj.value=1;
	}else{
		var wdId = obj.id;
		var url = "../../suWhDetail/queryNumber.action";
		var data = {"wdId":wdId};
		$.post(url,data,function(mes){
			if(numbers>mes){
				layer.msg("最大数量为"+mes);
				obj.value=mes;
			}
		},"json")
	}
}

/**
 * 批发商品删除
 * @param id 商品ID
 * @returns
 */
function remove(id){
	 layer.alert('确定删除此商品么？', {
	      closeBtn: 1    // 是否显示关闭按钮
	      ,anim: 1 //动画类型
	      ,btn: ['确认','取消'] //按钮
	      ,yes:function(){
	    	    $("#sc"+id+"").parent().parent().remove();
	    		 //取得文本框的值
	    		 var aa = $("#comId").val();
	    		 //把文本框清空
	    		 $("#comId").val("")
	    		 //文本框的值按取消复选框的id来去除
	    		 var bb = aa.replace(id+"@",'');
	    		 //把值重新赋给文本框
	    		 $("#comId").val(bb);
	    		 //计算总价的方法
	    		 multipart();
	             layer.msg('删除成功！')
	      }
	     ,btn2:function(){
	         layer.msg('删除失败!')
	}});
}
/**
 * 计算小计
 * @returns
 */
function showTotal(obj){
	/** 获取当前文本框数量*/
	var userval = obj.value;
	var reg=/^[1-9]\d*$/;
	if(!reg.test(userval)){
		layer.msg("只能输入正整数!");
		obj.value=1;
		var pf = $(obj).parent().prev().text();
		$(obj).parent().next().text(parseFloat(pf));
		multipart();
	}else{
		var comId = $(obj).parent().parent().children().first().text();
		var data = {"comId":comId}
		var url = "../../wholeSale/queryInventory.action";
		$.post(url,data,function(mes){
			if(userval>mes){
				layer.msg("库存不足，该商品库存量为：  "+mes, {
				      icon: 5,
				      time: 1000 
				    }
				); 
				obj.value=mes;
				var pf = $(obj).parent().prev().text();
				$(obj).parent().next().text(parseFloat(pf*mes));
				multipart();
			}else{
				var pf = $(obj).parent().prev().text();
				$(obj).parent().next().text(parseFloat(pf*userval));
				multipart();
			}
		},"json")
	}
}
/**
 * 计算总价
 * @returns
 */
function multipart(){
	var sum = 0;
	$.each($(".sum"),function(index,item){
		money = $(this).html();
		sum+=parseFloat	(money);
	});
	if(sum==0){
		$("#heji").html("0");
	}else{
		$("#heji").html(sum);
	}
}
/**
 * 查询所有类型
 * @returns
 */
function queryType(){
	var url = "../../comtype/query.action";
	$.post(url,null,function(mes){
		$.each(mes,function(i,item){
			$("#snacksType").append("<option>"+item.typeName+"</option>");
			load();
		})
	},"json")
}
/**
 * 退出清空文本框
 * @returns
 */
function exit(){
	$("#snacks").val("");
	$("#snacksType").val("");
	$("#snacksNum").val("");
	$("#snacksNum2").val("");
	$("#result").val("");
	load();
	//关闭所有页面层
	layer.closeAll('page');
}

layui.use(['form', 'layedit', 'laydate','table'], function(){
  var table = layui.table
  ,laydate = layui.laydate
  ,form = layui.form
  ,layer = layui.layer
  ,layedit = layui.layedit;
  
  //开始时间
  var startDate=laydate.render({
      elem: '#date',//开始时间ID
      type: 'date',//时间类型
      max:0,//设置一个默认最大值(为当前时间)
      done: function(value, date){
          endDate.config.min ={
              year:date.year,
              month:date.month-1, 
              date: date.date,
          };
      }
  });
  //结束时间
  var endDate= laydate.render({
      elem: '#time',//选择器结束时间
      type: 'date',//时间类型
      max:0,//设置一个默认最大值(为当前时间)
      done: function(value,date){
          startDate.config.max={
              year:date.year,
              month:date.month-1,
              date: date.date,
          }
      }
  });
  
  //监听工具条
  table.on('tool(demo)', function(obj){
    var da = obj.data;
    if(obj.event === 'detail'){
    	layer.open({
	         type: 2	 
	        ,title: '批发订单详情'
	        ,area: ['800px', '400px']
    		,offset: 'auto'
	        ,content:['../../page/zyf/detail/wsDetail.html?whId='+da.whId+'','on']
	        ,end : function() {
	        	
			}
	    });
     }else if (obj.event === 'shdetail'){
    	 layer.open({
	         type: 2	 
	        ,title: '批发审核详情'
	        ,area: ['800px', '400px']
    		,offset: 'auto'
	        ,content:['../../page/zyf/detail/wsAuditDetail.html?whId='+da.whId+'','on']
	        ,end : function() {
	        	
			}
	    });
     }else if (obj.event === 'quere'){
    	 var ii = layer.alert('确认批发么？', {
		       closeBtn: 1    // 是否显示关闭按钮
		      ,anim: 1 //动画类型
		      ,btn: ['确认批发','残忍拒绝'] //按钮
		      ,yes:function(){
		    	  layer.close(ii);
		    	  var index = layer.load(0, {time: 8*1000});
		    	  var urls = "../../wholeSale/findInventory.action";
		     	  var datas = {"whId":da.whId};
		    	  $.post(urls,datas,function(mes){
		    		  if(mes.state==1){
		    			  layui.use('layer',function(){
		    			        layer=layui.layer;
		    			        layer.msg('库存不足,批发失败!',{
		    			            icon:5,
		    			            anim:6
		    			        });
		    			    })
		    			 layer.close(index);
		    		  }else{
		    			  var url = "../../wholeSale/confirmWholesale.action";
				     	  var data = {"whId":da.whId};
				     	 $.post(url,data,function(mes){
				    		 if(mes.state==1){
				    			 $(".layui-laypage-btn")[0].click();//当前表格刷新
				    			    layui.use('layer',function(){
				    			        layer=layui.layer;
				    			        layer.msg('批发成功!',{
				    			            icon:6,
				    			            anim:1
				    			        });
				    			    })
				    			    layer.close(index);
				    		 }else{
				    			 layui.use('layer',function(){
				    			        layer=layui.layer;
				    			        layer.msg('批发失败!',{
				    			            icon:5,
				    			            anim:6
				    			        });
				    			    })
				    			 layer.close(index);
				    		 }
				    	 },"json") 
		    		  }
		    	  },"json")
		      }
		     ,btn2:function(){
		         layer.msg('批发失败')
    	}});
     }else if(obj.event === 'refunds'){
    	 $("#thdd").val(da.whId)
    	 layer.open({
	         type: 1	 
	        ,title: '批发订单退货'
	        ,offset: 'auto'
	        ,area: ['650px', '300px']
	        ,content:$('#tui')
	        ,success: function(layero){
	        	//重载表单
	        	table.reload('test3', {
					page: {
						curr: 1 //重新从第 1 页开始
					} ,where: {
						whId: da.whId,
			        }
				});
	        },end : function() {
	        	exit();
	        	$("#tbody2").html("");
	        	$("#comIds").val("");
	        	$("#tui").hide();
			}
	    });
     }else if(obj.event==="thdetail"){
    	 layer.open({
	         type: 2	 
	        ,title: '批发退货订单详情'
	        ,area: ['800px', '400px']
    		,offset: 'auto'
	        ,content:['../../page/zyf/detail/returnDetail.html?whId='+da.whId+'','on']
	        ,end : function() {
	        	
			}
	    });
     }else if(obj.event === 'tuidetail'){
    	 layer.open({
	         type: 2	 
	        ,title: '批发退货审核详情'
	        ,area: ['800px', '400px']
    		,offset: 'auto'
	        ,content:['../../page/zyf/detail/returnAuditDetail.html?whId='+da.whId+'','on']
	        ,end : function() {
	        	
			}
	    });
     }else if(obj.event === 'qurt'){
    	 var ii = layer.alert('确认退货么？', {
		       closeBtn: 1    // 是否显示关闭按钮
		      ,anim: 1 //动画类型
		      ,btn: ['确认退货','残忍拒绝'] //按钮
		      ,yes:function(){
		    	  layer.close(ii);
		    	  var index = layer.load(0, {time: 8*1000});
		    	  var urls = "../../wholeSale/findMoney.action";
		     	  var datas = {"whId":da.whId};
		    	  $.post(urls,datas,function(mes){
		    		  if(mes.state==1){
		    			  layui.use('layer',function(){
		    			        layer=layui.layer;
		    			        layer.msg('财务金额不足,退货失败!',{
		    			            icon:5,
		    			            anim:6
		    			        });
		    			    })
		    			 layer.close(index);
		    		  }else{
		    			  var url = "../../wholeSale/returnedPurchase.action";
				     	  var data = {"whId":da.whId};
				     	 $.post(url,data,function(mes){
				    		 if(mes.state==1){
				    			 $(".layui-laypage-btn")[0].click();//当前表格刷新
				    			    layui.use('layer',function(){
				    			        layer=layui.layer;
				    			        layer.msg('退货成功!',{
				    			            icon:6,
				    			            anim:1
				    			        });
				    			    })
				    			    layer.close(index);
				    		 }else{
				    			 layui.use('layer',function(){
				    			        layer=layui.layer;
				    			        layer.msg('退货失败!',{
				    			            icon:5,
				    			            anim:6
				    			        });
				    			    })
				    			 layer.close(index);
				    		 }
				    	 },"json") 
		    		  }
		    	  },"json")
		      }
		     ,btn2:function(){
		         layer.msg('退货失败!')
		     }});
     	}
  });
  /**
   * 加入批发订单
   */
  table.on('tool(insCom)', function(obj){
	  var da = obj.data;
	  if(obj.event === 'zj'){
		  var data = {"comId":da.comId}
		  var url = "../../wholeSale/queryInventory.action";
		  $.post(url,data,function(mes){
			  if(mes==0){
				  layer.msg("亲 ~ 不好意思库存不足 ！ ", {
				      icon: 5,
				      time: 1000 ,
				      anim:6
				    }
				  ); 
			  }else{
				  var　result = true;
				  $.each($("#comId").val().split("@"),function(index,item){
					  if(item==da.comId){
						  layer.msg("亲 ~ 您已经加入了此商品 ！ ", {
						      icon: 5,
						      time: 1000 ,
						      anim:6
						    }
						  ); 
						  result = false;
					  }
				  });
				  if(result){
					  $("#comId").val($("#comId").val()+da.comId+"@");
					  $("#tbody").append("<tr>" +
			  				"<td>"+da.comId+"</td>" +
			  				"<td>"+da.comName+"</td>" +
			  				"<td>"+da.comUnit+"</td>" +
			  				"<td>"+da.ciRetail+"</td>" +
			  				"<td>"+da.ciTrade+"</td>" +
			  				"<td><input type='text' onkeyup='showTotal(this)' value='1' maxlength='5' style='height:30px;border:0;width:100px;border-radius:5px;'></td>" +
			  				"<td class='sum'>"+da.ciTrade+"</td>" +
			  				"<td><a id='sc"+da.comId+"' class='layui-btn layui-btn-danger layui-btn-xs' onclick=remove(\'"+da.comId+"\')>删除</a></td>" +
			  				"</tr>");
					  multipart();
					  layer.msg("亲 ~ 加入成功 ！ ", {
					      icon: 6,
					      time: 1000 
					    }
					  ); 
				  }
			  }
		  },"json");
	  }
  });
  /**
   * 条件查询
   */
  var $ = layui.$, active = {
		  reload: function(){
		      var date = $('#date');
		      var time = $('#time');
		      var oper = $('#oper');
		      var state= $('#state');
		      //执行重载
		      table.reload('idTest', {
		        page: {
		          curr: 1 //重新从第 1 页开始
		        }
		        ,where: {
		        	startTime: date.val(),
		        	endTime: time.val(),
		        	oper: oper.val(),
		        	whState:state.val()
		        }
		      });
		},
		suwhdetail:function(){
		  var snacks= $('#snacks');
	      var snacksType= $('#snacksType');
	      var snacksNum= $('#snacksNum');
	      var snacksNum2= $('#snacksNum2');
		  //执行重载
	      table.reload('test2', {
	        page: {
	          curr: 1 //重新从第 1 页开始
	        }
	        ,where: {
	        	comName: snacks.val(),
	        	typeName: snacksType.val(),
	        	startPrice: snacksNum.val(),
	        	endPrice:snacksNum2.val()
	        }
	      });
		}
 };
  
	$('.demoTable .layui-btn').on('click', function(){
		var type = $(this).data('type');
		active[type] ? active[type].call(this) : '';
	});
	
	/**
	 * 点击增加的方法
	 */
  $('#insert').on('click', function(){
	  layer.open({
	         type: 1	 //此处以iframe举例
	        ,title: '批发订单增加'
	        ,offset: 'auto'
	        ,area: ['1100px', '520px']
	        ,content:$('#add')
	        ,success: function(layero){
	        	//重载表单
	        	table.reload('test2', {
					page: {
						curr: 1 //重新从第 1 页开始
					}
				});
	        },end : function() {
				exit();
				$("#tbody").html("");
	        	$("#heji").html("0");
	        	$("#comId").val("");
	        	$("#add").hide();
	        	$("#selectButton").click();
			}
	    });
	
  });
  /**
   * 增加批发订单
   */
  $('#submitButton').on('click', function(){
	  if($('#tbody').find('tr').text()==""){
		  layer.msg("请选中要批发的商品!");
	  }else{
		  layer.confirm('确认提交订单么',{title:"确认操作"}, function(index){
			  layer.close(index);
			    var index2 = layer.load(0, {time: 10*1000}); 
			    var html = ''; 
				$('#tbody').find('tr').each(function () {
					$(this).find('td').each(function () {  
						html += $(this).text()+',';  
					}) 
				  html += $(this).find('td:eq(5) input').val()+'#'; 
				})
				  var url="../../wholeSale/add.action";
				  var data={"str":html,"sum":$("#heji").text()};
				  $.post(url,data,function(mes){
					  if(mes.state==0){
						  exit();
						  $("#add").hide();
						  $(".layui-laypage-btn")[0].click();//当前表格刷新
						  parent.layer.msg('增加订单成功，请等待审核！', {
						      icon: 6
						  });
						  layer.close(index2); 
					  }else{
						  parent.layer.msg('增加订单失败！', {
						      icon: 5
						  });
						  layer.close(index2); 
					  }
				  },"json");
		  });
	  }
  });
  
  $("#submitButton2").on('click',function(){
	  if($("#result").val()==""){
		  layer.msg("请输入退货原因!");
	  }else{
		  var ss = true;
		  $.each($(".thnum"),function(i,item){
			  if($(item).val()==""||$(item).val()==null){
				  layer.msg("亲 ~ 请输入商品退货数量 ！ ", {
				      icon: 5,
				      time: 1000 ,
				      anim:6
				    });
				  ss = false;
			  }
		  })
		  if(ss){
			  layer.confirm('确认提交订单么',{title:"确认操作"}, function(index){
				  layer.close(index);
				  setTimeout(() => {
					  	var index2 = layer.load(0, {time: 10*1000}); 
						var html = "";
						$.each(table.cache.test3,function(i,item){
							html +=item.comId+","+item.wdNumber+","+$("#"+item.wdId).val()+"&";
						})
						var url = "../../wholeSale/refunds.action";
						var data = {"str":html,"result":$("#result").val(),"whId":$("#thdd").val()}
						$.post(url,data,function(mes){
							  if(mes.state==0){
								  $("#thdd").val("");
								  $("#tui").hide();
								  //关闭所有页面层
								  layer.closeAll('page');
								  $(".layui-laypage-btn")[0].click();//当前表格刷新
								  parent.layer.msg('增加退货订单成功，请等待审核！', {
								      icon: 6
								  });
								  layer.close(index2); 
							  }else{
								  parent.layer.msg('增加订单失败！', {
								      icon: 5
								  });
								  layer.close(index2); 
							  }
						},"json")
					 }, 100);
			  });
		  }
	  }
  })
});
/**
 * 渲染
 * @returns
 */
function load() {
	 var form = layui.form
	 form.render();
}